package hkr.se1.budgetapp;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class EntriesDataSource {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_DATE, MySQLiteHelper.COLUMN_NOTE,
			MySQLiteHelper.COLUMN_CATEGORY, MySQLiteHelper.COLUMN_AMOUNT };

	public EntriesDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public void deleteAll() {
		List<Entry> a = getAllEntries();
		for (int i = 0; i < a.size(); i++) {
			deleteEntry(a.get(i));
		}
	}

	public void deleteEntry(Entry entry) {
		long id = entry.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_ENTRIES, MySQLiteHelper.COLUMN_ID
				+ " = " + id, null);
	}

	public boolean saveEntry(Entry entry) {

		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_DATE, entry.getDate());
		values.put(MySQLiteHelper.COLUMN_NOTE, entry.getNote());
		values.put(MySQLiteHelper.COLUMN_CATEGORY, entry.getCategory());
		values.put(MySQLiteHelper.COLUMN_AMOUNT, entry.getAmount());

		long insertId = database.insert(MySQLiteHelper.TABLE_ENTRIES, null,
				values);
		if (insertId == -1) {
			return false;
		} else {
			return true;
		}
	}

	public List<Entry> getAllEntries() {
		List<Entry> entries = new ArrayList<Entry>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_ENTRIES,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();

		while (!cursor.isAfterLast()) {
			Entry entry = cursorToEntries(cursor);
			entries.add(entry);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return entries;
	}

	public List<Entry> getTopEntries() {
		List<Entry> entries = new ArrayList<Entry>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_ENTRIES,
				allColumns, null, null, null, null, MySQLiteHelper.COLUMN_ID
						+ " DESC");

		cursor.moveToFirst();
		
		if (cursor.getCount() < 5) {
			cursor.moveToLast();
		} else {
			cursor.moveToPosition(4);
		}
		while(!cursor.isBeforeFirst()){
			Entry entry = cursorToEntries(cursor);
			entries.add(entry);
			cursor.moveToPrevious();
		}
		return entries;
	}

	private Entry cursorToEntries(Cursor cursor) {
		Entry entry = new Entry();
		entry.setId(cursor.getLong(0));
		entry.setDate(cursor.getString(1));
		entry.setNote(cursor.getString(2));
		entry.setCategory(cursor.getString(3));
		entry.setAmount(cursor.getInt(4));
		return entry;
	}
}